import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 零售退货流水（顾客退货）
export const useReturnStore = defineStore('return', () => {
  const STORAGE_KEY = 'erppos_returns'
  const returns = ref([])

  const persist = () => localStorage.setItem(STORAGE_KEY, JSON.stringify(returns.value))

  const initialize = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    if (cached) {
      try { returns.value = JSON.parse(cached) || [] } catch { returns.value = [] }
    } else {
      returns.value = []
      persist()
    }
  }

  const todayStr = () => new Date().toISOString().slice(0, 10)
  const genSn = () => {
    const date = todayStr().replace(/-/g, '')
    const seq = String(Date.now()).slice(-6)
    return `RT${date}${seq}`
  }

  const createReturn = ({ items, operator = '系统', reason = '顾客退货', channel = '线下', buyer = '散客', refundMethod = 'original' }) => {
    const now = new Date().toISOString()
    const amount = items.reduce((s, it) => s + Number(it.price || 0) * Number(it.qty || 0), 0)
    const rec = {
      id: 'R' + Date.now(),
      sn: genSn(),
      createdAt: now,
      operator,
      reason,
      channel,
      buyer,
      amount: Number(amount.toFixed(2)),
      refundMethod,
      items: items.map(x => ({
        productId: x.productId || '',
        code: x.code || '',
        name: x.name || '',
        qty: Number(x.qty || 0),
        price: Number(x.price || 0),
      })),
    }
    returns.value.unshift(rec)
    persist()
    return rec
  }

  const filtered = (filters = {}) => {
    const s = (filters.search || '').toLowerCase()
    const [start, end] = filters.range || []
    return returns.value.filter(r => {
      if (s && !(r.sn || '').toLowerCase().includes(s) && !(r.buyer || '').toLowerCase().includes(s)) return false
      if (start || end) {
        const d = (r.createdAt || '').slice(0, 10)
        if (start && d < start) return false
        if (end && d > end) return false
      }
      return true
    })
  }

  const statsToday = computed(() => {
    const today = todayStr()
    const list = returns.value.filter(r => (r.createdAt || '').startsWith(today))
    return {
      count: list.length,
      amount: list.reduce((s, x) => s + Number(x.amount || 0), 0),
    }
  })

  const exportReturns = (list = null) => {
    const exportList = list || returns.value
    const headers = ['单号','日期','买家','金额','渠道','操作员','原因']
    const rows = exportList.map(r => [r.sn, r.createdAt, r.buyer || '', r.amount, r.channel || '', r.operator || '', r.reason || ''])
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `退货_${todayStr()}.csv`
    link.click()
  }

  return {
    returns,
    initialize,
    createReturn,
    filtered,
    statsToday,
    exportReturns,
  }
})


